<template>
  <div v-loading="pageLoading" :class="{'mobile-detail-wrap':showMobilePage}" class="customer-adjustment-detail-container">
    <template v-if="!permissionDenied">
      <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="detailData.isExpedited"/>
      <explanation :explanation="explanationObj" :countdown="true" @queryProcessData="queryProcessData" />
      <div class="customer-adjustment-content small-padding">
        <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
        <!-- 申请信息 -->
        <applyInfo :apply-info="applyInfo" />
        <!-- 当前客户信息 -->
        <customerInfo :detail-data="detailData.customerInfo" is-detail />
        <!-- 申请调整内容 -->
        <adjustContent :range-list="rangeList" :detail-data="detailData.adjustContent" />
        <!-- 调整后客户信息 -->
        <adjustedInfo :detail-data="detailData.adjustedInfo" />
      </div>
      <ExamineAndApprove
        ref="examineAndApproveRef"
        :version="version"
        :show-print="isShowPrint"
        :print-data="printData"
        :disabled="disabled"
        :process-id="processId"
        :main-id="customerAdjustmentId"
        :hide-press-btn="hidePressBtn"
        :get-comments-api="getCustomerAdjustmentComments"
        :comment-add-api="customerAdjustmentCommentAdd"
        :process-revocation-api="customerAdjustmentProcessRevocation"
        :process-recall-api="customerAdjustmentProcessRecall"
        :process-audit-api="customerAdjustmentProcessAudit"
        :create-user="createUser"
        :business-type="BUSINESS_TYPE.CUSTOMER_ADJUSTMENT"
        :process-type="PROCESS_TYPE.CUSTOMER_ADJUSTMENT"
        :audit-schedule-data="auditScheduleData"
        :senders="senders"
        :default-aduitor-list="[{id: applyInfo.proposerId, userName: applyInfo.proposer}]"
        :approval-module-type="APPROVAL_MODULE_TYPE.CUSTOMER_ADJUSTMENT"
        :is-apply="isApply"
        next-approve-module-id="id"
        redirect-url="/client/customerAdjustmentDetail"
        detail-page-router-name="customerAdjustmentDetail"
        edit-page-router-name="customerAdjustmentEdit"
        @toBack="toBack"
        @setProcessData="setProcessData"
        @getAuditSchedule="getAuditSchedule"
        @queryProcessData="freshProcessData"
        @handlePressSend="handlePressSend"
        @handleCreateNew="handleCreateNew"
        @handleSendMsg="handleSendMsg"
        @handleSender="handleSender"
        @handleModify="handleModify('customerAdjustmentEdit',{id: customerAdjustmentId},{remodifyId: processId})"
        @getHistoryDetail="getHistoryDetail"
        @setCurrentVersion="setCurrentVersion"
        @freshDetail="queryInfo"
        @handleCancelPress="handleCancelPress"
      />
    </template>
    <DeniedPlaceholder v-else />
    <ding-ding-dialog
      ref="pressSendDialogRef"
      :btn1="'确认加急'"
      :btn2="'取消'"
      :show-send-checkbox="false"
      :select-with-user-load="false"
      :default-list="pressDefaultList"
      redirect-url="/client/customerAdjustmentDetail"
      summary-title="加急原因"
      title="催办通知"
      @handelOK="toSend" />
  </div>
</template>

<script>
// components
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import explanation from '@/components/Common/explanation';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
import applyInfo from './module/applyInfo';
import customerInfo from '../create/module/customerInfo';
import adjustContent from './module/adjustContent';
import adjustedInfo from '../create/module/adjustedInfo';
// api
import {
  clientAdjustmentDetail,
  getCustomerAdjustmentComments,
  customerAdjustmentCommentAdd,
  customerAdjustmentProcessRevocation,
  customerAdjustmentProcessRecall,
  customerAdjustmentProcessAudit
} from '@/api/customer';
// mixins
import schedule from '@/mixins/schedule';
// tools
import { mapState } from 'vuex';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { BUSINESS_TYPE, PROCESS_TYPE } from '@/utils/const/process';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';
import { formatTag } from '@/filters/dept';
import { moneyFilter } from '@/filters/number';
// img
import revokeImg from '@/assets/auditProcess/process_status_3.png';
export default {
  components: {
    ProgressStep,
    explanation,
    ExamineAndApprove,
    applyInfo, customerInfo, adjustContent, adjustedInfo
  },
  filters: { formatTag, moneyFilter },
  mixins: [schedule],
  data() {
    return {
      revokeImg,
      PROGRESS_STEP,
      isRevoke: false,
      permissionDenied: false,
      customerAdjustmentCommentAdd,
      getCustomerAdjustmentComments,
      customerAdjustmentProcessRevocation,
      customerAdjustmentProcessRecall,
      customerAdjustmentProcessAudit,
      stepActiveId: PROGRESS_STEP.PENDING,
      BUSINESS_TYPE, PROCESS_TYPE, APPROVAL_MODULE_TYPE,
      applyInfo: {},
      isShowPrint: true,
      hidePressBtn: false,
      detailData: {
        isExpedited: 0,
        customerInfo: {
          customerName: '',
          customerLevel: '',
          levelColor: '',
          customerBusiness: '',
          group: '',
          remark: '',
          oweData: {},
          tag: null,
          clientStatusStr: '',
          accountPeriod: null,
          customerSource: '',
          sale: ''
        },
        adjustContent: {},
        adjustedInfo: {
          customerLevel: '',
          levelColor: '',
          oweData: {},
          loanPeriod: null
        }
      },
      rangeList: [],
      processData: {},
      pageLoading: false,
      disabled: false,
      processId: '' // 流程id
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    createUser() {
      let user = { id: this.applyInfo.creatorId, userName: this.applyInfo.creator };
      if (this.userInfo.id === this.applyInfo.creatorId) {
        user = this.userInfo;
      }
      return user;
    },
    isApply() { // 申请人
      const proposerId = this.applyInfo && this.applyInfo.proposerId ? this.applyInfo.proposerId : '';
      return proposerId && this.userInfo.id === proposerId;
    },
    printData() {
      const { adjustedInfo, customerInfo } = this.detailData;
      let result = _.cloneDeep(this.detailData);
      delete result.adjustedInfo;
      delete result.customerInfo;
      result = {
        ...result,
        attachment: result.attachment && result.attachment.length ? formatTag(result.attachment) : null,
        loanQuota: result.loanQuota ? moneyFilter(result.loanQuota, true, '', true) : null,
        loanPeriod: result.loanPeriod ? `${result.loanPeriod}天` : null,
        quotaApplication: result.quotaApplication ? moneyFilter(result.quotaApplication, true, '', true) : null,
        payPeriodApplication: result.payPeriodApplication ? `${result.payPeriodApplication}天` : null
      };
      if (customerInfo) {
        result = {
          ...customerInfo,
          customerGroup: customerInfo.group ? formatTag(customerInfo.group) : null,
          customerTag: customerInfo.tag ? formatTag(customerInfo.tag) : null,
          accountPeriod: `${customerInfo.accountPeriod}天`,
          customerLevelInfo: customerInfo.customerLevel,
          customerDepartment: customerInfo.department && customerInfo.department.length && formatTag(customerInfo.department),
          customerQuota: customerInfo.oweData && (customerInfo.oweData.availableAmount || customerInfo.oweData.availableAmount === 0) ? `${moneyFilter(customerInfo.oweData.availableAmount, true, '', true)}/${moneyFilter(customerInfo.oweData.totalAmount, true, '', true)}` : null,
          ...result
        };
      }
      if (adjustedInfo) {
        const { customerLevel, loanPeriod, oweData } = adjustedInfo;
        result = {
          adjustCustomerLevel: customerLevel || null,
          adjustLoanPeriod: `${loanPeriod}天`,
          adjustLoanQuota: oweData && (oweData.availableAmount || oweData.availableAmount === 0) ? `${moneyFilter(oweData.availableAmount, true, '', true)}/${moneyFilter(oweData.totalAmount, true, '', true)}` : null,
          ...result
        };
      }
      return result;
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.initRouteData();
      this.queryProcessData();
    },
    initRouteData() {
      this.customerAdjustmentId = this.$route.query.id;
      this.processId = this.$route.query.processId;
      if (!this.customerAdjustmentId || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    setProcessData(processData) {
      this.processData = processData;
    },
    freshProcessData() {
      this.queryProcessData(false);
    },
    queryProcessData(isInit = true) {
      this.queryInfo(isInit);
      this.getAuditSchedule();
      this.$nextTick(() => {
        this.$refs['examineAndApproveRef'] && this.$refs['examineAndApproveRef'].getProcessList();
      });
    },
    freshDetail() {
      this.queryInfo(false);
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'customerAdjustment' });
      }
    },
    handleDetailData(res, isInit) {
      if (res.code === 200) {
        const { data } = res;
        const detailData = _.cloneDeep(data);
        const { adjustmentInfo, customerLevel, quotaApplication, loanPeriod, loanQuota, payPeriodApplication, levelColor } = detailData;
        this.applyInfo = detailData;
        if (!data.customerInfo) {
          this.disabled = true;
          this.isShowPrint = false;
          this.hidePressBtn = true;
          if (isInit) this.$message.warning('客户已被删除');
        } else {
          this.disabled = false;
          this.detailData = detailData;
          this.detailData.customerInfo = data.customerInfo;
        }
        if (adjustmentInfo) this.detailData.adjustedInfo = adjustmentInfo;
        this.rangeList = data.rangeList;
        this.detailData.adjustContent = { customerLevel, quotaApplication, loanPeriod, loanQuota, payPeriodApplication, levelColor };
        if (data.processStatus === 3) { // 3为撤销
          this.stepActiveId = PROGRESS_STEP.PENDING;
          this.isRevoke = true;
        } else {
          this.stepActiveId = data.processStatus;
          this.isRevoke = false;
        }
        this.pageLoading = false;
      }
    },
    queryInfo(isInit = true) {
      this.pageLoading = true;
      clientAdjustmentDetail(this.customerAdjustmentId).then(res => {
        this.handleProcessCheck(res.data.processId);
        this.handleDetailData(res, isInit);
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.pageLoading = false;
      });
    },
    // 再次发起（复制）新打开页面
    handleCreateNew() {
      const routeUrl = this.$router.resolve({
        name: 'customerAdjustmentEdit',
        params: { id: this.customerAdjustmentId },
        query: { reapplyId: this.processId, createNew: 1 }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.customer-adjustment-detail-container {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding-bottom: 55px;
  min-height: calc(100vh - 64px);
  .customer-adjustment-content{
    position: relative;
    padding: 16px 24px 56px;
  }
  &::v-deep {
    .explanation-container{
      .explanation{
        padding-left: 32px!important;
      }
    }
    .customer-form {
      .el-form-item {
        .el-form-item__label {
          color: #999;
        }
      }
    }
  }
  .revoke-img{
    position: absolute;
    width: 80px;
    height: 80px;
    right: 56px;
    top: 33px;
    z-index: 999;
  }
}
</style>
